import { onCLS, onFCP, onFID, onINP, onLCP, onTTFB, Metric } from "web-vitals";

const SCORE_RANGE_LCP: [number, number] = [2500, 4500];
const SCORE_RANGE_FID: [number, number] = [100, 300];
const SCORE_RANGE_CLS: [number, number] = [0.1, 0.25];
const SCORE_RANGE_FCP: [number, number] = [1.8, 3];
const SCORE_RANGE_INP: [number, number] = [200, 500];
const SCORE_RANGE_TTFB: [number, number] = [800, 1800];

const Quetas = ["FCP", "TTFB", "LCP", "CLS", "FID", "INP"] as const;

const round = (value: number, decimals: number) => {
  return Number(Math.round(Number(value + "e" + decimals)) + "e-" + decimals);
};

export function mapMetric(metric: Metric) {
  const isWebVital = Quetas.includes(metric.name);
  return {
    [metric.name]: isWebVital ? round(metric.value, metric.name === "CLS" ? 4 : 0) : metric.value,
    [`${metric.name}Rating`]: metric.rating,
  };
}

export const onVitals = (saveMetric: (metric: Metric) => void) => {
  onLCP(saveMetric);
  onFID(saveMetric);
  onCLS(saveMetric);
  onTTFB(saveMetric);
  onINP(saveMetric);
  onFCP(saveMetric);
};

export function generateUniqueId() {
  return `v1-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
}
